from base_class import base_class
import inspect
import sys,os,json
import paho.mqtt.client as mqtt
a=0
class mqtt_class(base_class):
    def __on_connect(self,client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT broker")
            client.subscribe("topic1")
        else:
            print("Failed to connect, return code %d\n", rc)
    def __on_message(self,client, userdata, message):
        print(message.topic,{str(message.payload.decode('utf-8'))})

    def _add_topic(self):
        pass
    def init(self,**kwargs):
        self.broker_address=kwargs.get("broker_address")
        self.broker_port=kwargs.get("broker_port")
        self.fast_topics={}#topic快速搜索字典
        self.topic_info={}
        self.a=0
    def add_topic(self,topic,info):
        self.mqtt_client.subscribe(topic)#订阅
        new_topics=self.fast_topics
        for i in topic:
            new_topics2=new_topics.get(i)
            if new_topics2 is None:
                new_topics[i]={}
                new_topics=new_topics[i]
            else:
                new_topics=new_topics2
        new_topics['value']=info 
    #绑定topic
    def mqtt_handler(self,id_,topic, handle):  
        self.add_topic(topic,{"id":id_, "handle": handle})
        self.topic_info()
        #id 唯一id 如 (用户id,目录id,项目id,流程id,组件id) 
    #取消绑定
    def mqtt_unhandler(self,topic):
        pass
    def find_topic(self,topic):
        match_topic=''
        now_topic=self.fast_topics
        for i in topic:
            # print('find',i,topics)
            if '#'in now_topic:
                return {"match_topic":match_topic+'#',"info":now_topic['#']['value']}
            else:
                match_topic+=i
                now_topic=now_topic.get(i)
                if now_topic is None:return#没有匹配到
        if now_topic.get('value') is True:return {"match_topic":match_topic,"info":now_topic['value']}
        elif now_topic.get('#')is not None:return {"match_topic":match_topic+'#',"info":now_topic['#']['value']}
        else:return None#没有匹配到
    #添加topic以及相关响应处理

    #匹配topic的时间   100w条topic匹配一条topic的时间在0s左右
    def on_message(self, client, userdata, msg):  
        topic = msg.topic  
        payload = msg.payload.decode()  
        now_topic_info=self.find_topic(topic)#查找topic
        #如果对topic进行处理
        if now_topic_info is not None:
            self.a+=1
            print(self.a,"匹配到topic:",now_topic_info)
            print("\t\t数据:",payload)   
    def handle(self,gev_obj,socket,address):
        while True:
            data = socket.recv(1024)
            if not data:
                break
            if data[0]==10:
                new_data=data[1:]
                json_val=json.loads(new_data.decode('utf-8') )
                print(json_val)
                self.add_topic(json_val['topic'],json_val['info'])
                socket.sendall(new_data)
    def run_server(self):
        print("start server")
        # 创建 MQTT 客户端实例
        self.mqtt_client = mqtt.Client()
        # 连接到 MQTT 服务器
        self.mqtt_client.connect(self.broker_address, self.broker_port)
        self.mqtt_client.on_message = self.on_message
        # 开始循环监听
        self.mqtt_client.loop_start()

        #与其他进程进行通信的socket服务（用于接收数据
        self._recv()

if __name__=="__main__":
    a=mqtt_class(**{
        'broker_address':"127.0.0.1",
        'broker_port':1883,
        "project_dir_path":os.path.dirname(os.path.abspath(__file__)),
        "recv_port":5555,
        "process_id":None,
        "temp_name":"mqtt_test"
        
    })
    obj=a.create_obj()
    print(obj)